<?php

namespace app\adminapi\controller;

use think\Controller;
use think\Request;

class Login extends BaseApi
{
    # 验证码接口
    public function verify()
    {
        $uniqid = uniqid("login", true);
        $res = [
            "url" => captcha_src($uniqid),
            "uniqid" => $uniqid
        ];
        $this->ok($res);
    }
    # 登录
    public function login(Request $request){
        # 接收参数
        $params = input();
        // dump($params);
        # 参数检测
        $validata = $this->validate($params,[
            "username|用户名" => "require",
            "password|密码" => "require",
            // "uniqid|验证码编号" => "require",
            // "code" => "require",
            // 'code|验证码' => 'require|captcha:'.$params['uniqid'],
        ]);
        # 判断他传入的数据是不有误
        if($validata !== true){
            $this->fail($validata);
        }
        # 判断他传入的验证码是否正确
        // dump($params["uniqid"]);
        // dump($params["code"]);die;
        // if(!captcha_check($params['code'], $params['uniqid'])){
        //     $this->fail('验证码错误', 400);
        // }
        $password = jiami_password($params["password"]);
        $file = \app\common\model\Admin::where("username",$params["username"])->where("password",$password)->find();
        if(!$file){
            $this->fail("账号或密码错误，请重新输入");
        }
        $token = \tools\jwt\Token::getToken($file->id);
        // dump($token);die;
        $data = [
            "username" => $file->username,
            "email" => $file->email,
            "token" => $token,
            "user_id" => $file->id,
            "nickname" => $file->nickname
        ];
        $this->ok($data);
    }
    # 退出登录
    public function logout(){
        # 清空token 将token存入到文件中或者服务器或session中去
        $token = \tools\jwt\Token::getRequestToken();
        // dump($token);die;
        # 判断他是否已经存在token了如果不存在那就默认一个空的数组进行一个添加
        $delete_token = cache("delete_token") ?:[];
        $delete_token[] = $token;
        # 存储到文件中  
        cache("delete_token",$delete_token,86400);
        $this->ok([],200,"退出登录成功");
    }
}
